package me.zhengjie.inter.service.impl;

import cn.hsaf.common.utils.StringUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.base.OrgWeightVo;
import me.zhengjie.base.WeightVo;
import me.zhengjie.business.domain.*;
import me.zhengjie.business.domain.vo.ZhsqPgtsVo;
import me.zhengjie.business.repository.AdlZhsqRepository;
import me.zhengjie.business.repository.FpryRepository;
import me.zhengjie.business.repository.HljgRepository;
import me.zhengjie.business.repository.ZhsqRepository;
import me.zhengjie.business.service.GsglService;
import me.zhengjie.business.service.SbgsService;
import me.zhengjie.business.service.YbryService;
import me.zhengjie.business.service.dto.*;
import me.zhengjie.business.service.mapstruct.ZhsqMapper;
import me.zhengjie.config.DebugProperties;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.inter.service.MpZhsqService;
import me.zhengjie.modules.system.domain.vo.GsglScale;
import me.zhengjie.modules.system.repository.GsglScaleRepository;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

/**
 * @description 服务接口
 * @author xiahongbo
 * @date 2022-07-10
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class MpZhsqServiceImpl implements MpZhsqService {

    private final AdlZhsqRepository adlZhsqRepository;
    private final LocalStorageRepository localStorageRepository;
    private final GsglScaleRepository gsglScaleRepository;

    private final ZhsqRepository zhsqRepository;
    private final ZhsqMapper zhsqMapper;

    @Autowired
    private final SbgsService sbgsService;
    @Autowired
    private final YbryService ybryService;

    @Autowired
    private GsglService gsglService;

    private final UserService userService;
    private final FpryRepository fpryRepository;

    @Override
    public Map<String, Object> queryAll(ZhsqQueryCriteria criteria, Pageable pageable) {
        Page<Zhsq> page = zhsqRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        List<Zhsq> list = page.getContent();
        for (int i = 0; i < list.size(); i++) {
            log.info("录入时间: {}", list.get(i).getLrsj());
        }
        return PageUtil.toPage(page.map(zhsqMapper::toDto));
    }

    @Override
    public List<ZhsqDto> queryAll(ZhsqQueryCriteria criteria) {
        return zhsqMapper.toDto(zhsqRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
    @Override
    public Map<String, String> queryDyqx(Long id) {
        Zhsq zhsq = zhsqRepository.findById(id).orElseGet(Zhsq::new);
        Map<String, String> map = new HashMap<String, String>();

        Date dykkrq = zhsq.getBisZhsqDykkrq();
        Date dyjsrq = zhsq.getBisZhsqDyjsrq();

        map.put("currentDate", DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN));
        map.put("dykkrq", DateUtil.format(dykkrq, DatePattern.NORM_DATE_PATTERN));
        map.put("dyjsrq", DateUtil.format(dyjsrq, DatePattern.NORM_DATE_PATTERN));
        return map;
    }

    @Override
    public JSONObject checkCreate(String sfzh) {
        JSONObject obj = new JSONObject();
        obj.put("flag", "1");
        obj.put("msg", "校验通过");
        List<Zhsq> list = zhsqRepository.findByBisZhsqSnrySfzOrderByBisZhsqId(sfzh);

        System.out.println(list);

        if(list != null && list.size() != 0) {

            for (int i = 0; i < list.size(); i++) {

                Zhsq zhsq0 = list.get(i);
                String zhlb = zhsq0.getBisZhsqZhlb();

                if("03".equals(zhlb)) {

                    log.info("移动端[MpZhsqServiceImpl - checkCreate]--------------- {} ", zhsq0);
                    String zhzt = zhsq0.getBisZhsqZt();
                    if(// DefaultUtil.ZHZT_ZPBH.equals(zhzt) ||
                            DefaultUtil.ZHZT_DFP.equals(zhzt) ||
                                    DefaultUtil.ZHZT_DZX.equals(zhzt) ||
                                    DefaultUtil.ZHZT_ZXZ.equals(zhzt) ||
                                    DefaultUtil.ZHZT_YZX.equals(zhzt) ||
                                    DefaultUtil.ZHZT_YRD.equals(zhzt) ||
                                    DefaultUtil.ZHZT_GSZ.equals(zhzt) ||
                                    DefaultUtil.ZHZT_YGS.equals(zhzt) ||
                                //    DefaultUtil.ZHZT_NPG.equals(zhzt) ||
                                //    DefaultUtil.ZHZT_NHF.equals(zhzt) ||
                                    DefaultUtil.ZHZT_DSP.equals(zhzt) ||
                                    DefaultUtil.ZHZT_DQY.equals(zhzt)  ) {

                        // 提示状态
                        obj.put("flag", "0");
                        obj.put("msg", "失能老人["+zhsq0.getBisZhsqSnryXm()+"]正在申请居家照护");
                        break;
                    } else if (DefaultUtil.ZHZT_YQY.equals(zhzt)) {
                        Date dykkrq = zhsq0.getBisZhsqDykkrq();
                        Date dyjsrq = zhsq0.getBisZhsqDyjsrq();
                        dyjsrq = DateTimeUtil.addMonths(dyjsrq, -1);
                        log.info("移动端[MpZhsqServiceImpl - checkCreate]据身份证查询，待遇开始 {}, 待遇结束 {} ", dykkrq, dyjsrq);

                        Date currentDate = DateTimeUtil.getNow();

                        if(currentDate.after(dykkrq) && currentDate.before(dyjsrq)) {
                            obj.put("flag", "0");
                            obj.put("msg", "失能老人["+zhsq0.getBisZhsqSnryXm()+"]正在享受居家待遇期");
                            break;
                        }
                        // 提示状态
                    }
                } else if("01".equals(zhlb)) {
                    log.info("移动端[MpZhsqServiceImpl - checkCreate]--------------- {} ", zhsq0);
                    String zhzt = zhsq0.getBisZhsqZt();
                    if(// DefaultUtil.ZHZT_ZPBH.equals(zhzt) ||
                            DefaultUtil.ZHZT_DFP.equals(zhzt) ||
                                    DefaultUtil.ZHZT_DZX.equals(zhzt) ||
                                    DefaultUtil.ZHZT_ZXZ.equals(zhzt) ||
                                    DefaultUtil.ZHZT_YZX.equals(zhzt) ||
                                    DefaultUtil.ZHZT_ZXPG.equals(zhzt) ||
                                    DefaultUtil.ZHZT_ZXFH.equals(zhzt) ) {

                        // 提示状态
                        obj.put("flag", "0");
                        obj.put("msg", "失能老人["+zhsq0.getBisZhsqSnryXm()+"]正在申请居家照护");
                        break;
                    } else if (DefaultUtil.ZHZT_YRD.equals(zhzt)) {
                        Date dykkrq = zhsq0.getBisZhsqDykkrq();
                        Date dyjsrq = zhsq0.getBisZhsqDyjsrq();
                        dyjsrq = DateTimeUtil.addMonths(dyjsrq, -1);
                        log.info("移动端[MpZhsqServiceImpl - checkCreate]据身份证查询，待遇开始 {}, 待遇结束 {} ", dykkrq, dyjsrq);

                        Date currentDate = DateTimeUtil.getNow();

                        if(currentDate.after(dykkrq) && currentDate.before(dyjsrq)) {
                            obj.put("flag", "0");
                            obj.put("msg", "失能老人["+zhsq0.getBisZhsqSnryXm()+"]正在享受机构待遇期");
                            break;
                        }
                        // 提示状态
                    }
                }

            }

            int zpcs = zhsqRepository.queryApplyCount(sfzh);
            if(zpcs == 3) {
                obj.put("flag", "0");
                obj.put("msg", "30天内，累计申请超过3次。请30天以后再申请");
                return obj;
            }

            List<Object> list1 = zhsqRepository.checkPgtg(sfzh);
            if (list1 != null && list1.size() != 0) {
                Object zhsq1 = list1.get(0);
                Object[] arr = (Object[]) zhsq1;
                String xm = (String)arr[0];
                String zt = (String)arr[1];
                String dyksrq = (String)arr[2];
                String pgsj = (String)arr[3];
                String dysyts = (String)arr[4];
                String pgsyts = (String)arr[5];
                if("13".equals(zt)) {
                    if(Double.parseDouble(dysyts) < 150) {
                        log.info("移动端[MpZhsqServiceImpl - checkCreate]据身份证查询，最近的一次审核是否超过150天 getLrsj : {}" , arr[1]);
                        obj.put("flag", "0");
                        obj.put("msg", "失能老人[" + xm + "]于["+dyksrq+"]签约。根据市医保要求，150天内不允许居家照护申请");
                    }
                } else if("-4".equals(zt)) {

                    List<Object> list2 = zhsqRepository.checkPgcs(sfzh);
                    int pgcsCnt = list2.size();
                    Object object = list2.get(0);
                    Object[] arr2 = (Object[]) object;
                    String lrsj = (String)arr2[0];
                    String ts = (String)arr2[1];
                    if(pgcsCnt == 2) {
                        log.info("移动端[MpZhsqServiceImpl - checkCreate]据身份证查 lrsj : {}, ts:{}" , lrsj, ts);
                        if(Double.parseDouble(ts) < 180) {
                            obj.put("flag", "0");
                            obj.put("msg", "失能老人[" + xm + "]评估退回了两次，最后一次评估时间为[" + lrsj + "]。根据市医保要求，180天内不允许居家照护申请");
                        }
                    } else if (pgcsCnt == 1) {

                        log.info("移动端[MpZhsqServiceImpl - checkCreate]据身份证查 lrsj : {}, ts:{}" , lrsj, ts);
 /*
                        if(Double.parseDouble(ts) > 5 && Double.parseDouble(ts) <= 180) {
                            obj.put("flag", "0");
                            obj.put("msg", "失能老人[" + xm + "]评估退回了一次，最后一次评估时间为[" + lrsj + "]。根据市医保要求，超过5天不允许提出居家复评");
                        } else
*/
                        // 2024年4月份，只可以评估一次
                        if(Double.parseDouble(ts) > 180) {
                            obj.put("flag", "2");
                            obj.put("msg", "失能老人[" + xm + "]评估退回了一次，最后一次评估时间为[" + lrsj + "]。请点击【照护申请】按钮，重新申请");
                        } else {
                            obj.put("flag", "0");
                            obj.put("msg", "失能老人[" + xm + "]评估退回了一次，最后一次评估时间为[" + lrsj + "]。根据市医保要求，180天内不允许居家照护申请");
                        }
                    } else if (pgcsCnt >= 3) {
                        if(Double.parseDouble(ts) < 180) {
                            obj.put("flag", "0");
                            obj.put("msg", "评估退回多次。根据市医保要求，180天内不允许居家照护申请");
                        }
                    }
                } else {
                    if(Double.parseDouble(pgsyts) <= 180) {
                        obj.put("flag", "0");
                        obj.put("msg", "失能老人[" + xm + "]于["+pgsj+"]评估通过，尚未签约。根据市医保要求，180天内不允许居家照护申请");
                    }
                }
            } else {
                List<Object> list2 = zhsqRepository.checkPgcs(sfzh);
                if (list2 != null && list2.size() != 0) {
                    int pgcsCnt = list2.size();
                    Object object = list2.get(0);
                    Object[] arr2 = (Object[]) object;
                    String lrsj = (String)arr2[0];
                    String ts = (String)arr2[1];
                    String xm = (String)arr2[2];
                    if(pgcsCnt == 2) {
                        log.info("移动端[MpZhsqServiceImpl - checkCreate]据身份证查 lrsj : {}, ts:{}" , lrsj, ts);
                        if(Double.parseDouble(ts) < 180) {
                            obj.put("flag", "0");
                            obj.put("msg", "失能老人[" + xm + "]评估退回了两次，最后一次评估时间为[" + lrsj + "]。根据市医保要求，180天内不允许居家照护申请");
                        }
                    } else if (pgcsCnt == 1) {

                        log.info("移动端[MpZhsqServiceImpl - checkCreate]据身份证查 lrsj : {}, ts:{}" , lrsj, ts);
                     /*   if(Double.parseDouble(ts) > 5 && Double.parseDouble(ts) <= 180) {
                            obj.put("flag", "0");
                            obj.put("msg", "失能老人[" + xm + "]评估退回了一次，最后一次评估时间为[" + lrsj + "]。根据市医保要求，超过5天不允许提出居家复评");
                        } else */
                        if(Double.parseDouble(ts) > 180) {
                            obj.put("flag", "2");
                            obj.put("msg", "失能老人[" + xm + "]评估退回了一次，最后一次评估时间为[" + lrsj + "]。请点击【照护申请】按钮，重新申请");
                        } else {
                            obj.put("flag", "0");
                            obj.put("msg", "失能老人[" + xm + "]评估退回了一次，最后一次评估时间为[" + lrsj + "]。根据市医保要求，180天内不允许居家照护申请");
                        }
                    } else if (pgcsCnt >= 3) {
                        if(Double.parseDouble(ts) < 180) {
                            obj.put("flag", "0");
                            obj.put("msg", "评估退回多次。根据市医保要求，180天内不允许居家照护申请");
                        }
                    }
                } else {
                    List<Object> list3 = zhsqRepository.checkZpsp(sfzh);
                    if (list3 != null && list3.size() != 0) {
                        Object object = list3.get(0);
                        Object[] arr2 = (Object[]) object;
                        String ts = (String) arr2[1];
                        String xm = (String) arr2[2];
                        String zpjg = (String) arr2[3];
                        obj.put("flag", "2");
                        obj.put("msg", "失能老人[" + xm + "]自评退回，回退原因[" + zpjg + "]。请点击【照护申请】按钮，重新申请");
                    }
                }
            }

        }

        return obj;
    }

    @Override
    @Transactional
    public ZhsqDto create(Zhsq resources, String ids) {
        /*
        int count = zhsqRepository.queryApplyCount(resources.getBisZhsqSnrySfz());
        log.info("移动端[MpZhsqServiceImpl - create]查询失能患者30内的申请次数 {} ", count);
        if(count >= 3) {
            throw new BadRequestException("失能老人["+resources.getBisZhsqSnryXm()+"]30天内的申请超过3次，30天以后再申请");
        }
*/
        log.info("移动端[MpZhsqServiceImpl - create]新增照护申请 {} ", resources);
        log.info("移动端[MpZhsqServiceImpl - create]新增照护图片 {} ", ids);
      /*  ZhsqDto zhsqDtoPage = zhsqMapper.toDto(resources);
        Zhsq zhsq = zhsqMapper.toEntity(zhsqDtoPage);*/

        Long userid = SecurityUtils.getCurrentUserId();
        int age = CalculateAge.getCurrentAge(resources.getBisZhsqSnrySfz());


        // 获取随机的评估公司ID

        List<WeightVo> pgListWeight = new ArrayList<>();
        List<GsglScale> gsglScales = gsglScaleRepository.findListByDeptId(resources.getBisZhsqHldzSsqx());
        for (GsglScale sbgs : gsglScales) {
            WeightVo vo = new WeightVo();
            vo.setId(sbgs.getGsglId());
            vo.setPrize_weight(Double.parseDouble(sbgs.getWeightScale()));
            pgListWeight.add(vo);
        }
        int pgPrizeIndex = WeightUtil.getPrizeIndex(pgListWeight);
        WeightVo pgPrizeDto = pgListWeight.get(pgPrizeIndex);

        // 先获取实体中的ADL量表信息
        List<AdlZhsq> list = resources.getAdlZhsqs();
        // 清空实体中ADL量表信息
        resources.setAdlZhsqs(new ArrayList<>());
        // resources.setBisSbgsId(sbgsId);
        resources.setBisPggsId(pgPrizeDto.getId());
        resources.setBisUserId(userid);
        resources.setBisZhsqNl(String.valueOf(age));
        resources.setBisZhsqSnryXb("1".equals(resources.getBisZhsqSnryXb()) ? "女" : "男");

        log.info("[MpZhsqServiceImpl - create]照护类别：居家自主护理[03]{} ");
        resources.setBisZhsqZhlb("03");

        String[] adlIds = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            AdlZhsq adl = list.get(i);
            adlIds[i] = adl.getAdlXmxxId();
        }
        log.info("移动端[MpZhsqServiceImpl - create]格式化自评主键 {} ", adlIds);
        String fs = adlZhsqRepository.queryScore(adlIds);

        // adl量表自评分数
        resources.setBisZhsqAdlPc("402883ba943fefb7019444d38ee10002");
        resources.setBisZhsqAdl(fs);
        double fsInt = Double.parseDouble(fs);
        if(fsInt <= 40) {
            log.info("移动端[MpZhsqServiceImpl - create]查询自评分数小于等于40分，分数达标：{} ", fs);
            resources.setBisZhsqZt(DefaultUtil.ZHZT_DSP);
        } else {
            log.info("移动端[MpZhsqServiceImpl - create]查询自评分数大于40分，分数不达标：{} ", fs);
            resources.setBisZhsqZt(DefaultUtil.ZHZT_YCX);
        }


        // 增加支付开启状态
//        BIS_ZHSQ_HLJG_ID
        String bisPggsId = resources.getBisPggsId();
        String isPay = gsglService.findByBisGsglId(bisPggsId).getIsPay();

        resources.setIsPay("1".equals(isPay) ? "1" : "0");
        resources.setPayStatus("0");


        // 根据当前申请日期，判断是新增还是延期
        Zhsq tempZhsq = zhsqRepository.queryHomeSqlb(resources.getBisZhsqSnrySfz(), DateTimeUtil.getDateTime(new Date(), DateTimeUtil.DEFAULT_DATE_FORMAT));
        if(tempZhsq == null) {
            resources.setBisZhsqSqlb("10");
        } else {
            resources.setBisZhsqSqlb("20");
        }

        // 新增自评
        Zhsq newZhsq = zhsqRepository.save(resources);
        for (int i = 0; i < list.size(); i++) {
            AdlZhsq adl = list.get(i);
            adl.setBisAdlZhsqId(IdUtil.simpleUUID());
            adl.setZhsq(newZhsq);
            adl.setBisUserId(userid);
            adlZhsqRepository.save(adl);
            log.info("移动端[MpZhsqServiceImpl - create]新增ADL量表自评结果 {} ", adl);
        }
        // 新增照片

        if(ids != null && !ids.equals("")){

            String[] picIds = ids.split(",");
            for (String picId:picIds) {

                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                localStorageRepository.save(localStorage);
            }
        }

        List<OrgWeightVo> listWeight = userService.queryUserWeight(220101l, "54");
        int prizeIndex = WeightUtil.getOrgWeigth(listWeight);
        OrgWeightVo prizeDto = listWeight.get(prizeIndex);
        Long userId = prizeDto.getId();
        String userName = prizeDto.getName();
        log.info("移动端[MpZhsqServiceImpl - create]--------------- 居家提交照护申请 - 随机分配 - 初审人员ID {}，初审人员姓名 {} ", userId, userName);

        Fpry fpry = new Fpry();
        fpry.setBisFpryId(IdUtil.simpleUUID());
        fpry.setBisFpryZhsqId(newZhsq.getBisZhsqId());
        fpry.setBisFpryRyglId(userId);
        fpry.setBisFpryRyglXm(userName);
        fpry.setBisFpryFpsj(new Date());
        fpry.setBisFpryZt("0");
        fpryRepository.save(fpry);
        return zhsqMapper.toDto(newZhsq);
    }

    @Override
    @Transactional
    public ZhsqDto updateZhsq(Zhsq resources, String ids) {
        int count = zhsqRepository.checkZpspWtg(resources.getBisZhsqId());
        log.info("移动端[MpZhsqServiceImpl - create]自评审批未通过5次，无法继续提交 {} ", count);
        if(count >= 5) {
            throw new BadRequestException("失能老人["+resources.getBisZhsqSnryXm()+"]自评审批未通过5次，无法继续提交");
        }

        log.info("移动端[MpZhsqServiceImpl - create]新增照护申请 {} ", resources);
        log.info("移动端[MpZhsqServiceImpl - create]新增照护图片 {} ", ids);

        Long userid = SecurityUtils.getCurrentUserId();

//        Zhsq zhsq = zhsqRepository.findById(resources.getBisZhsqId()).get();


        if(resources.getBisZhsqZt().equals("-4") || resources.getBisZhsqZt().equals("-5")){
            /*
            List<WeightVo> listWeight = new ArrayList<>();
            SbgsQueryCriteria criteria = new SbgsQueryCriteria();
            List<SbgsDto> sbgsDtoList = sbgsService.queryAll(criteria);
            for (SbgsDto sbgs : sbgsDtoList) {
                WeightVo vo = new WeightVo();
                vo.setId(sbgs.getBisGsglId());
                vo.setPrize_weight(Double.parseDouble(sbgs.getBz()));
                listWeight.add(vo);
            }
            int prizeIndex = WeightUtil.getPrizeIndex(listWeight);
            WeightVo prizeDto = listWeight.get(prizeIndex);*/

            GsglScale gsglScale = gsglScaleRepository.findByDeptId(resources.getBisZhsqHldzSsqx());
            String sbgsId = gsglScale.getGsglId();

            resources.setBisSbgsId(sbgsId);
            resources.setBisPggsId(sbgsId);


            // 先获取实体中的ADL量表信息
            List<AdlZhsq> list = resources.getAdlZhsqs();
            // 清空实体中ADL量表信息
            resources.setAdlZhsqs(new ArrayList<>());

            String[] adlIds = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                AdlZhsq adl = list.get(i);
                adlIds[i] = adl.getAdlXmxxId();
            }
            log.info("移动端[MpZhsqServiceImpl - create]格式化自评主键 {} ", adlIds);
            String fs = adlZhsqRepository.queryScore(adlIds);
            log.info("移动端[MpZhsqServiceImpl - create]查询自评分数 {} ", fs);

            // adl量表自评分数
            resources.setBisZhsqAdl(fs);
            for (int i = 0; i < list.size(); i++) {
                AdlZhsq adl = list.get(i);
                adl.setBisAdlZhsqId(IdUtil.simpleUUID());
                adl.setZhsq(resources);
                adl.setBisUserId(userid);
                adlZhsqRepository.save(adl);
                log.info("移动端[MpZhsqServiceImpl - create]新增ADL量表自评结果 {} ", adl);
            }

        }else if(resources.getBisZhsqZt().equals("00")){

        }
        resources.setBisZhsqZt(DefaultUtil.ZHZT_DSP);

        // 新增自评
        Zhsq newZhsq = zhsqRepository.save(resources);

        // 新增照片

        if(ids != null && !ids.equals("")){

            String[] picIds = ids.split(",");
            for (String picId:picIds) {

                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                localStorageRepository.save(localStorage);
            }
        }
        return zhsqMapper.toDto(newZhsq);
    }
    @Override
    public String queryScore(String[] adlIds){
        return adlZhsqRepository.queryScore(adlIds);
    }
    /**
     * 校验参保信息
     * 1、校验参保状态
     * 2、校验是否缴费
     * 3、校验人员类型
     * 4、校验是否住院
     * 5、校验是否正在享受待遇
     * @param sfzh
     * @return
     */
    @Override
    public JSONObject checkCbInfo(String sfzh) {

        JSONObject jsonObject = new JSONObject();

        if(DebugProperties.rysfz.indexOf(sfzh) == -1 ) {
            // 在测试人员中没indexof到，执行校验

            JSONArray array = new JSONArray();
            if(!DebugProperties.debug) {
                log.info("移动端[MpZhsqServiceImpl - queryHomeCbInfo]身份证: {} ", sfzh);
                Map<String,Object> map = ybryService.queryHomeCbInfo(sfzh);
                log.info("移动端[MpZhsqServiceImpl - queryHomeCbInfo]校验参保信息 {} ", map);
                List<YbryDto> rsList = (List<YbryDto>)map.get("content");

                YbryDto ybryDto = rsList.get(0);

                JSONObject cbJson = new JSONObject();
                JSONObject jfJson = new JSONObject();
                JSONObject rylxJson = new JSONObject();
                JSONObject dyJson = new JSONObject();

                String msg = "";

                // 校验参保状态
                if ("停保".equals(ybryDto.getAac031())) {
                    msg += "※参保状态【已停保】，无法申请照护待遇\n";
                    cbJson.put("msg", "参保状态【已停保】，无法申请照护待遇");
                    cbJson.put("code", 0);
                } else {
                    cbJson.put("msg", "参保状态【参保中】");
                    cbJson.put("code", 1);
                }
                // 校验是否缴费
                if ("".equals(ybryDto.getClctClag())) {
                    msg += "※缴费状态【未缴费】，无法申请照护待遇\n";
                    jfJson.put("msg", "缴费状态【未缴费】，无法申请照护待遇");
                    jfJson.put("code", 0);
                } else {
                    jfJson.put("msg", "缴费状态【已缴费】");
                    jfJson.put("code", 1);
                }
                // 校验人员类型
                if ("离休或一级保健对象".equals(ybryDto.getAkc021())) {
                    msg += "※人员类型【离休或一级保健对象】，无法申请照护待遇\n";
                    rylxJson.put("msg", "人员类型【离休或一级保健对象】，无法申请照护待遇");
                    rylxJson.put("code", 0);
                } else {
                    rylxJson.put("msg", "人员类型【普通人员】");
                    rylxJson.put("code", 1);
                }
                // 校验是否住院
                // 校验是否正在享受待遇
                if (!"".equals(ybryDto.getAkb021())) {
                    msg += "※此人正在【"+ybryDto.getAkb021()+"】享受照护待遇\n";
                    dyJson.put("msg", "此人正在【"+ybryDto.getAkb021()+"】享受照护待遇");
                    dyJson.put("code", 0);
                } else {
                    dyJson.put("msg", "尚未享受照护待遇");
                    dyJson.put("code", 1);
                }
                // 校验是否正在享受待遇
                if ("2".equals(ybryDto.getPausType()) || "3".equals(ybryDto.getPausType())) {
                    msg += "※此人【"+ybryDto.getChgReaDscr()+"】\n";
                    dyJson.put("msg", "此人【"+ybryDto.getChgReaDscr()+"】");
                    dyJson.put("code", 0);
                } else {
                    dyJson.put("msg", "没有封锁期");
                    dyJson.put("code", 1);
                }
                array.add(cbJson);
                array.add(jfJson);
                array.add(rylxJson);
                array.add(dyJson);

                int allCode = cbJson.getIntValue("code") &
                        jfJson.getIntValue("code") &
                        rylxJson.getIntValue("code") &
                        dyJson.getIntValue("code");

                msg = allCode == 1 ? "通过" : msg;
            /*
            allCode = 0;
            msg += "1、参保状态【已停保】，无法申请照护待遇\n";
            msg += "2、缴费状态【未缴费】，无法申请照护待遇\n";
            msg += "3、人员类型【离休或一级保健对象】，无法申请照护待遇\n";
            msg += "4、此人正在【测试机构】享受照护待遇\n";
*/
                jsonObject.put("allMsg", msg);
                jsonObject.put("allCode", allCode);
            } else {
                jsonObject.put("allMsg", "通过");
                jsonObject.put("allCode", 1);
            }
        } else {
            // 测试人员，不执行校验
            log.info("移动端[MpZhsqServiceImpl - checkCbInfo]测试人员：{}, 测试人员身份证: {} ", DebugProperties.rysfz, sfzh);

            jsonObject.put("allMsg", "通过");
            jsonObject.put("allCode", 1);
            return jsonObject;
        }

        log.info("移动端[MpZhsqServiceImpl - checkCbInfo]校验结果 {} ", jsonObject);
        return jsonObject;
    }

    @Override
    public List<Long> queryZhidsByUserId(Long userId) {
        return zhsqRepository.queryZhidsByUserId(userId);
    }

    @Override
    public Zhsq queryByBisZhsqId(Long valueOf) {
        return zhsqRepository.findById(valueOf).orElseGet(Zhsq::new);
    }

    @Override
    public void updateZhsqPayStatus(String payStatus, Long bisZhsqId) {
        zhsqRepository.updatePayStatus(payStatus, bisZhsqId);
    }
}
